import React, {Component} from 'react';
import {matchPath, Route as ReactRoute, __RouterContext as RouterContext} from "react-router";

export default class Route extends ReactRoute {

    static defaultProps = {
        cache: false
    };

    render() {

        if (!this.props.cache) {
            return super.render();
        }

        return (
            <RouterContext.Consumer>
                {context => {
                    const location = this.props.location || context.location;
                    let match = this.props.computedMatch
                        ? this.props.computedMatch // <Switch> already computed the match for us
                        : this.props.path
                            ? matchPath(location.pathname, this.props)
                            : context.match;

                    const props = {...context, location, match};

                    let {children, component, render, _switchItemMatch} = this.props;

                    // Preact uses an empty array as children by
                    // default, so use null if that's the case.
                    if (Array.isArray(children) && children.length === 0) {
                        children = null;
                    }

                    if (_switchItemMatch === false) {
                        match = null;
                    }

                    if (!this._component && match) {
                        this._component = props.match
                            ? children
                                ? typeof children === "function"
                                    ? children(props)
                                    : children
                                : component
                                    ? React.createElement(component, props)
                                    : render
                                        ? render(props)
                                        : null
                            : typeof children === "function"
                                ? children(props)
                                : null;
                    }

                    return (
                        <RouterContext.Provider value={props}>
                            {
                                match ?
                                    <span>
                                        {
                                            this._component
                                        }
                                    </span> :
                                    <span style={({display: 'none'})}>
                                        {
                                            this._component
                                        }
                                </span>
                            }
                        </RouterContext.Provider>
                    );
                }}
            </RouterContext.Consumer>
        );
    }
}
